package com.yugao.fintech.antelope.filepreview.service.impl;

import com.yugao.fintech.antelope.filepreview.config.ConfigConstants;
import com.yugao.fintech.antelope.filepreview.filter.BaseUrlFilter;
import com.yugao.fintech.antelope.filepreview.model.FileAttribute;
import com.yugao.fintech.antelope.filepreview.model.FilePreviewRS;
import com.yugao.fintech.antelope.filepreview.service.FileHandlerService;
import com.yugao.fintech.antelope.filepreview.service.FilePreview;
import com.yugao.fintech.antelope.filepreview.utils.DownloadUtils;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import com.yugao.fintech.framework.core.response.Resp;
import com.yugao.fintech.framework.core.response.RetOps;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.net.URLEncoder;
import java.util.List;

/**
 * 处理pdf文件
 */
@Service
public class PdfFilePreviewImpl implements FilePreview {
    private final FileHandlerService fileHandlerService;
    private final OtherFilePreviewImpl otherFilePreview;
    private static final String FILE_DIR = ConfigConstants.getFileDir();

    public PdfFilePreviewImpl(FileHandlerService fileHandlerService, OtherFilePreviewImpl otherFilePreview) {
        this.fileHandlerService = fileHandlerService;
        this.otherFilePreview = otherFilePreview;
    }

    @Override
    public FilePreviewRS filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
        String fileName = fileAttribute.getName();
        String officePreviewType = fileAttribute.getOfficePreviewType();
        String baseUrl = BaseUrlFilter.getBaseUrl();
        String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "pdf";
        String outFilePath = FILE_DIR + pdfName;
        if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType)) {
            //当文件不存在时，就去下载
            if (!fileHandlerService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
                Resp<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
                if (!RetOps.of(response).isSuccess()) {
                    throw new BizException(response.getMsg());
                }
                outFilePath = response.getData();
                if (ConfigConstants.isCacheEnabled()) {
                    // 加入缓存
                    fileHandlerService.addConvertedFile(pdfName, fileHandlerService.getRelativePath(outFilePath));
                }
            }
            List<String> imageUrls = fileHandlerService.pdf2jpg(outFilePath, pdfName, baseUrl);
            if (imageUrls == null || imageUrls.size() < 1) {
                throw new BizException("pdf转图片异常，请联系管理员");
            }
            model.addAttribute("imgurls", imageUrls);
            model.addAttribute("currentUrl", imageUrls.get(0));
            if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType)) {
                return FilePreviewRS.builder().type(OFFICE_PICTURE_FILE_PREVIEW_PAGE).build();
            } else {
                return FilePreviewRS.builder().type(PICTURE_FILE_PREVIEW_PAGE).build();
            }
        } else {
            // 不是http开头，浏览器不能直接访问，需下载到本地
            if (url != null && !url.toLowerCase().startsWith("http")) {
                if (!fileHandlerService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
                    Resp<String> response = DownloadUtils.downLoad(fileAttribute, pdfName);
                    if (!RetOps.of(response).isSuccess()) {
                        throw new BizException(response.getMsg());
                    }
                    model.addAttribute("pdfUrl", fileHandlerService.getRelativePath(response.getData()));
                    if (ConfigConstants.isCacheEnabled()) {
                        // 加入缓存
                        fileHandlerService.addConvertedFile(pdfName, fileHandlerService.getRelativePath(outFilePath));
                    }
                } else {
                    pdfName = URLEncoder.encode(pdfName).replaceAll("\\+", "%20");
                    model.addAttribute("pdfUrl", pdfName);
                }
            } else {
                model.addAttribute("pdfUrl", url);
            }
        }
        return FilePreviewRS.builder().type(PDF_FILE_PREVIEW_PAGE).build();
    }
}
